<?php

use Biz\service\TradeMsg;
use Doraemon\cache\MsgCounter;
use Doraemon\cache\MsgLastCheck;
use Doraemon\tools\ActionLog;

class ListAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_REGISTER;
    const MSG_LIMIT = 30;

    public function main()
    {
        $start_id = $this->getRequest()->getQuery("start_id", 0);
        $msgList = TradeMsg::getMsgList($this->uid, $start_id, self::MSG_LIMIT);
        if ($msgList) {
            $lastCheckTime = MsgLastCheck::getAndSetLastCheckTime($this->uid, MsgLastCheck::TYPE_TRADE_MSG);
            $view = [
                "msg_list" => $this->formatView($msgList, $lastCheckTime),
                "is_over" => count($msgList) < self::MSG_LIMIT ? 1 : 0
            ];
        } else {
            $view = [
                "msg_list" => [],
                "is_over" => 1
            ];
        }
        MsgCounter::cleanMsgNum($this->uid, MsgCounter::TYPE_TRADEMSG);
        ActionLog::log($this->uid, ['type' => 'trade'], ActionLog::BIZ_READ_MESSAGE);
        $this->setSuccess($view);
    }

    private function formatView($msgList, $lastCheckTime)
    {
        return array_map(function ($msg) use ($lastCheckTime) {

            return [
                "id" => $msg["id"],
                "title" => $msg["title"],
                "detail" => $msg["detail"],
                "remark" => $msg["remark"],
                "img" => $msg["img"] ?: "",
                "link" => $msg["link"],
                "send_time" => strtotime($msg["send_time"]),
                "msg_code" => $msg["msg_code"],
                "is_new" => strtotime($msg["send_time"]) > $lastCheckTime ? 1 : 0,
            ];
        }, $msgList);
    }
}